package controllers

import (
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"io"
	"net/http"
	"os"
	"path/filepath"
	"strings"
)

func Upload(c *gin.Context) {
	uploadDir := os.Getenv("UPLOAD_DIR")
	contentType := c.ContentType()
	var file io.Reader
	//log.Println("contentType:", contentType)
	if strings.HasPrefix(contentType, "multipart/form-data") {
		// Define the maximum size of the formFile to read into memory (e.g., 10 MiB)
		err := c.Request.ParseMultipartForm(10 << 20) // 10 MiB
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"error": err.Error(),
			})
			return
		}

		// Retrieve the formFile from the posted form data
		formFile, _, err := c.Request.FormFile("formFile")
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"message": "Could not get uploaded formFile.",
				"error":   err.Error(),
			})
			return
		}
		defer formFile.Close()

		// Create a buffer to store the header of the formFile in
		//fileBuffer := make([]byte, 512)
		//_, err = formFile.Read(fileBuffer)
		//if err != nil {
		//	c.JSON(http.StatusInternalServerError, gin.H{
		//		"message": "Could not read formFile header.",
		//		"error":   err.Error(),
		//	})
		//	return
		//}
		//
		//// Reset the formFile read pointer.
		//_, err = formFile.Seek(0, 0)
		//if err != nil {
		//	c.JSON(http.StatusInternalServerError, gin.H{
		//		"message": "Could not reset formFile pointer.",
		//		"error":   err.Error(),
		//	})
		//	return
		//}

		file = formFile
	} else {
		file = c.Request.Body
	}

	// randomly generate unique file name
	filename := uuid.New().String()

	// Create the file at the server side
	out, err := os.Create(filepath.Join(uploadDir, filename))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"message": "Could not create file.",
			"error":   err.Error(),
		})
		return
	}
	defer out.Close()

	// Write the content from POSTed file to the created file
	_, err = io.Copy(out, file)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"message": "Could not write file.",
			"error":   err.Error(),
		})
		return
	}

	// File saved successfully. Return proper result.
	c.JSON(http.StatusOK, gin.H{
		"message": "File uploaded successfully!",
		"file":    filename,
	})
}
